# -*- encoding: utf-8 -*-

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

from . import _

import etude.plugins as ep
import etude.img as img
import gtk
import sys, cgi

HAVE_NOTIFY = True
try:
    import pynotify
except ImportError:
    HAVE_NOTIFY = False
    sys.stderr.write("pynotify (python-notify) not found, notifications disabled")

IMAGE_SIZE = 64

class DefaultNotify(ep.PluginExtra):

    """
    default notifications using pynotify
    """
    _short_name = "Libnotify Notifications"
    _show_name = _("Libnotify Notifications")
    _short_descr = ""
    _version = "0.1"
    _unique = "Libnotify_Notifications-0.1" # short name + version is enough, just to identify loaded

    def __init__(self, control):
        if HAVE_NOTIFY:
            self._interfaces = {'show_notify': self.interface_notify}
        
        ep.PluginExtra.__init__(self, control)
        if HAVE_NOTIFY:
            """If we have notification support, use it"""
            pynotify.init("Etude")
            self.bind(self.control.client, "e_playback_current_id",
                    self.song_changed)
            self.bind(self.control.client, "e_medialib_entry_changed",
                    self.entry_changed)
            self.bind(self.control, "g_interface_removed", self.interface_tray)
            self.bind(self.control, "g_interface_added", self.interface_tray)
            self.notification = pynotify.Notification(_("Now Playing"),
                    '', None)
            self.get_tray_icon()
            self.pb = gtk.icon_theme_get_default().load_icon('etude',
                    IMAGE_SIZE, 0)

    def entry_changed(self, widget, song_id):
        """if the current id changed, show the notification"""
        try:
            if song_id == self.control.client.playback.current_info['id']:
                self.song_changed(widget, song_id)
        except KeyError:
            pass
        return False

    def interface_notify(self, data=None):
        try:
            self.song_changed(None,
                    self.control.client.playback.current_info['id'])
        except KeyError:
            pass

    def get_tray_icon(self):
        if self.control.has_interface('tray_icon'):
            icons = self.control.use_interface('tray_icon')
            if len(icons) >0:
                self.notification.set_property('status-icon', icons[0])
                return False
        self.notification.set_property('status-icon', None)
        self.notification.clear_hints()
        return False

    def interface_tray(self, control, name):
        if name == 'tray_icon':
            self.get_tray_icon()

    def song_changed(self, widget, song_id):
        """the current playing song changed"""
        def _bindata_cb(value):
            pb = img.get_pixbuf_from_data(value, size=(IMAGE_SIZE, IMAGE_SIZE))
            self.show_notify(pb)
        nfo = self.control.client.playback.current_info
        if nfo.has_key('picture_front'):
            self.control.client.bindata.retrieve(nfo['picture_front'],
                    _bindata_cb)
            return False
        self.show_notify()

    def show_notify(self, pixbuf = None):
        """(re)show notification"""
        if pixbuf == None:
            pixbuf = self.pb
        """
        n = pynotify.Notification(_("Now Playing"), 
                cgi.escape("".join(
                    self.control.client.playback.current_info.get_custom_info("<smart>{\n<artist> (<album>)}"))), 
                None
                )
        """
        n = self.notification
        info = self.control.client.playback.current_info.get_custom_info(
                "<smart>{\n<artist> (<album>)}")
        n.set_property('body', cgi.escape("".join(info)))
        n.set_icon_from_pixbuf(pixbuf)
        n.show()

    def unload(self):
        """unload the plugin - uninit the pynotify"""
        ep.PluginExtra.unload(self)
        pynotify.uninit()



